package com.cyz.consumer;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

public class Consumer_Routing2 {
    public static void main(String[] args) throws IOException, TimeoutException {
//1.创建连接工厂
        ConnectionFactory factory=new ConnectionFactory();
        //2.设置参数
        factory.setHost("43.142.134.187");//ip地址 默认localhost
        factory.setPort(5672);//端口 默认值5672
        factory.setVirtualHost("/itcast");//虚拟机默认值 /虚拟机
        factory.setUsername("root");//用户名 默认guest
        factory.setPassword("root");//密码 默认guest
        //3.创建连接 connection
        Connection connection = factory.newConnection();
        //4.创建channel
        Channel channel = connection.createChannel();

        //5.队列已经声明一次了，这里不用再声明队列
        String queue2Name="routing_queue2";

        //6.接收消息
        Consumer consumer=new DefaultConsumer(channel){
            /*
                回调方法，当收到消息后，会自动执行该方法
                     1.consumerTag：标识
                     2.envelope：获取一些信息。交换机，路由key...
                     3.properties: 配置信息
                     4.body: 数据
             */
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                System.out.println("body:"+new String(body));//byte数组转string字符串
                System.out.println("将日志信息打印到控制台");
            }
        };
        channel.basicConsume(queue2Name,true,consumer);
        //关闭资源？不要，因为消费者要监听
    }
}
